package com.renwei.yunlong.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;

import com.google.gson.Gson;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.LubanOptions;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.renwei.yunlong.R;
import com.renwei.yunlong.activity.work.PhotoDisplayActivity;
import com.renwei.yunlong.adapter.ImageFileAdapter;
import com.renwei.yunlong.base.BaseFragment;
import com.renwei.yunlong.bean.HandleWorkBean;
import com.renwei.yunlong.bean.UpdateUserIconBean;
import com.renwei.yunlong.event.WorkHandlerEvent;
import com.renwei.yunlong.http.Api;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.LogUtil;
import com.renwei.yunlong.utils.UploadManger;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import github.opensource.dialog.prompt.PromptButton;
import github.opensource.dialog.prompt.PromptButtonListener;
import github.opensource.dialog.prompt.PromptDialog;


public class PhotoUpdataFragment extends BaseFragment implements ImageFileAdapter.OnItemDeleteClickListener,
        AdapterView.OnItemClickListener, InvokeListener, TakePhoto.TakeResultListener, HttpTaskListener {

    @Bind(R.id.gridview)
    GridView gridview;
    private ImageFileAdapter adapter;
    private List<UpdateUserIconBean> photos = new ArrayList<>();
    private Uri temmImageUrl;
    private PromptDialog promptDialog;
    private TakePhoto takePhoto;
    private InvokeParam invokeParam;
    private ArrayList<TImage> list;
    private int limt;

    @SuppressLint("ValidFragment")
    public PhotoUpdataFragment(boolean isOne) {
        boolean isOne1 = isOne;
    }

    public PhotoUpdataFragment() {
    }

    public List<UpdateUserIconBean> getPhotoInfo() {
        return photos;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_photo_updata;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        EventBus.getDefault().register(this);

        getTakePhoto().onCreate(savedInstanceState);
        promptDialog = new PromptDialog(getActivity());
        adapter = new ImageFileAdapter(getContext());
        adapter.setOnItemDeleteClickListener(this);
        gridview.setAdapter(adapter);
        gridview.setOnItemClickListener(this);
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onRefresh(WorkHandlerEvent event) {
        HandleWorkBean handleWorkBean = event.handleWorkBean;
        setData(handleWorkBean);
    }

    private void setData(HandleWorkBean handleWorkBean) {
        if (handleWorkBean.getMessage().getCode() == 200) {
            HandleWorkBean.Rows bean = handleWorkBean.getRows();
            if (bean != null) {
                if (!TextUtils.isEmpty(bean.getAttachPath())) {
                    String[] names = bean.getAttachName().split(",");
                    String[] paths = bean.getAttachPath().split(",");
                    String[] sizes = bean.getAttachSize().split(",");
                    for (int i = 0; i < paths.length; i++) {
                        UpdateUserIconBean e = new UpdateUserIconBean();
                        e.setPath(paths[i]);
                        e.setName(names[i]);
                        e.setSize(sizes[i]);
                        photos.add(e);
                        if ("1".equals(companyType)) {
                            adapter.addItem(Api.$().OWNER_FILE_URL + paths[i]);
                        } else if ("2".equals(companyType)) {
                            adapter.addItem(Api.$().SERVICE_FILE_URL + paths[i]);
                        }
                    }
                }
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        configCompress(takePhoto);
        return takePhoto;
    }

    //配置图像压缩相关
    private void configCompress(TakePhoto takePhoto) {
        CompressConfig config;
        LubanOptions option = new LubanOptions.Builder()
                .setMaxSize(1024000)
                .create();
        config = CompressConfig.ofLuban(option);
        config.enableReserveRaw(true);
        takePhoto.onEnableCompress(config, false);
    }

    @Override
    public void onDeleteClick(int position) {
        adapter.deleteItem(position);
        photos.remove(position);
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        if (position == (adapter.getmList() == null ? 0 : adapter.getmList().size())) { // 获取本地文件
            limt = 10 - (adapter.getCount() - 1);
            if (limt > 0) {
                PromptButton cancle = new PromptButton("取消", null);
                File file = new File(getActivity().getApplication().getCacheDir(), "/temp/" + System.currentTimeMillis() + ".jpg");
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                temmImageUrl = Uri.fromFile(file);
                LogUtil.e("imageUri " + temmImageUrl.toString());
                promptDialog.showAlertSheet("", true, cancle,
                        new PromptButton("打开相册", new PromptButtonListener() {
                            @Override
                            public void onClick(PromptButton button) {
                                takePhoto.onPickMultiple(limt);
                                // showTopWrongMsg("当前还可以选择"+ limt + "张图片附件");
                            }
                        }), new PromptButton("拍照", new PromptButtonListener() {
                            @Override
                            public void onClick(PromptButton button) {
                                takePhoto.onPickFromCapture(temmImageUrl);
                            }
                        }));
            } else {
                showTopWrongMsg("最多只能选择10张");
            }
        } else {
            // 展示图片
            ArrayList<String> list = new ArrayList<>();
            list.addAll(adapter.getmList());
            PhotoDisplayActivity.OpenActivity(getContext(), list, position);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(getActivity(), type, invokeParam, this);
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }


    @Override
    public void takeSuccess(TResult result) {
        try {
            list = result.getImages();
            for (TImage it : list) {
                File newFile = new File(it.getCompressPath());
                if (newFile.exists()) {
                    UploadManger manger = UploadManger.getManager();
                    if ("1".equals(companyType)) {
                        manger.uploadIcon(getContext(), newFile, this, ownerBean.getRows().getCompany().getVersionCode()
                                , ownerBean.getRows().getCompany().getCompanyCode());
                    } else if ("2".equals(companyType)) {
                        manger.uploadIcon(getContext(), newFile, this, serviceLoginBean.getRows().getCompany().getVersionCode()
                                , serviceLoginBean.getRows().getCompany().getCompanyCode());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            showCenterInfoMsg(this.getString(R.string.tip_file_is_not_exist));
        }
    }

    @Override
    public void takeFail(TResult result, String msg) {

    }

    @Override
    public void takeCancel() {

    }

    @Override
    public void onSuccess(int requestId, String result) {
        UpdateUserIconBean bean = new Gson().fromJson(result, UpdateUserIconBean.class);
        photos.add(bean);
        for (TImage image : list) {
            String image2Name = new File(image.getCompressPath()).getName();
            if (image2Name.equals(bean.getName())) {
                adapter.addItem(image.getCompressPath());
            }
        }
    }

    @Override
    public void onException(int requestId, String code) {
        showTopWrongMsg(getContext().getResources().getString(R.string.net_work_error));
    }
}
